package lab.gene.action;

import java.io.File;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lab.gene.pojo.GeneImageFile;
import lab.gene.service.impl.GeneImageFileServiceImpl;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

public class DeleteImageAction extends ActionSupport implements ServletResponseAware, ServletRequestAware {
	
	private static final long serialVersionUID = 1L;
	
	int id;
	private String userName = null;
	
	protected HttpServletResponse servletResponse;  
	@Override   
	public void setServletResponse(HttpServletResponse servletResponse) {   
		this.servletResponse = servletResponse;   
	}   
	
	protected HttpServletRequest servletRequest;   
	@Override   
	public void setServletRequest(HttpServletRequest servletRequest) {   
		this.servletRequest = servletRequest;   
	}
	
	public String execute() {
		
		 try{
			GeneImageFile imgFile = null;
	     	GeneImageFileServiceImpl service = new GeneImageFileServiceImpl();

	     	 if ((imgFile = service.getGeneImageFilesById(id)) != null) {
	     		 
	     		Cookie[] cookies = servletRequest.getCookies();
	    		String cookieName = "LabUser";
	    		if (cookies != null) {
	    			for (int i = 0; i < cookies.length; i++) {
	    				if (cookies[i].getName().equals(cookieName)) {
	    					userName = cookies[i].getValue();
	    					break;
	    				}
	    			}
	    		}
	    		//delete file
	    		String path = servletRequest.getSession().getServletContext().getRealPath("/");
	    		path = path + "upload\\"  + imgFile.getFileName();
	    		File file = new File(path);
	    		if (!file.delete()) return "error";
	    		service.deleteGeneImageFiles(id, userName);
	     	 }
	     	 else
	     	 {
	     		 return "error";
	     	 }
	      }catch(Exception e){
	         e.printStackTrace();
	         return "error";
	      }
		return "success";
	}

	

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}
	
	

}
